Popular Searches
Popular Course Categories
Popular Courses

Click and Hold

Mouse & Keyboard Actions

Click and Hold in Selenium WebDriver

Click and Hold is an advanced mouse interaction used in Selenium WebDriver when the mouse button needs to remain pressed while another action is performed. It is commonly used for drag-and-drop operations, sliders, custom mouse interactions, sortable components, drawing interfaces, and other web applications that depend on continuous mouse-button interaction.

In Selenium Java, the Actions class provides the clickAndHold() method. The method can be combined with moveToElement(), moveByOffset(), release(), and perform() to create realistic mouse interaction sequences.

Selenium Training Course | Register for Course Demo


1. What is Click and Hold?

Click and Hold is a mouse interaction in which the user presses the mouse button on an element and keeps the button pressed instead of immediately releasing it.

In Selenium, this interaction is commonly created using the clickAndHold() method of the Actions class.

Actions actions = new Actions(driver);

actions.clickAndHold(element).perform();


2. Why is Click and Hold Important?

Many modern web applications require the mouse button to remain pressed while the pointer is moved or another action is performed.

  • Supports drag-and-drop operations.
  • Supports custom mouse interactions.
  • Helps automate sliders and draggable controls.
  • Supports sortable UI components.
  • Can be used with drawing interfaces.
  • Provides greater control over mouse interactions.
  • Can be combined with other Actions methods.


3. Actions Class

The Actions class is Selenium's API for creating advanced keyboard and mouse interactions. It can be used for click and hold, drag and drop, hover, double click, right click, keyboard shortcuts, and other composite interactions.

Actions actions = new Actions(driver);


4. Basic Click and Hold Syntax

Actions actions = new Actions(driver);

actions.clickAndHold(element).perform();

The interaction can be understood as:

Locate Element

     ↓

Move Pointer

     ↓

Press Mouse Button

     ↓

Keep Button Pressed

     ↓

Perform Additional Action

     ↓

Release Mouse Button


5. Import Required Classes

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;


6. Simple Click and Hold Example

WebDriver driver = new ChromeDriver();

 

driver.get("https://example.com");

 

WebElement element = driver.findElement(

    By.id("source")

);

 

Actions actions = new Actions(driver);

 

actions.clickAndHold(element).perform();


7. Click and Hold with WebElement

The simplest approach is to locate a WebElement and pass it directly to clickAndHold().

WebElement element = driver.findElement(

    By.id("draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


8. Click and Hold Without Specifying an Element

The Actions API also supports clickAndHold() without an element. In this case, the action applies to the current mouse location.

new Actions(driver)

    .clickAndHold()

    .perform();

This form should be used carefully because the current pointer position must be appropriate for the intended interaction.


9. Click and Hold Followed by Move

A common use case is pressing the mouse button and then moving the pointer while keeping the button pressed.

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .perform();


10. Click and Hold Followed by Release

After holding the mouse button, the release() method can be used to release it.

new Actions(driver)

    .clickAndHold(source)

    .release()

    .perform();


11. Complete Click and Hold Sequence

A complete mouse sequence can combine movement, click and hold, movement to a destination, and release.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target)

    .release()

    .perform();


12. Click and Hold for Drag and Drop

Click and hold is one of the fundamental operations behind manual drag-and-drop automation.

Actions actions = new Actions(driver);

 

actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();


13. Click and Hold vs click()

Featureclick()clickAndHold()
Mouse buttonPressed and releasedPressed and kept down
Typical useNormal clickDrag or continuous interaction
Can combine with movementLimited for this purposeYes
Useful for drag and dropNoYes
Release required separatelyNoUsually yes


14. Click and Hold vs Double Click

AspectClick and HoldDouble Click
Mouse pressHeld continuouslyTwo clicks
MethodclickAndHold()doubleClick()
Typical useDrag and continuous actionsOpening or selecting items
ReleaseCan be performed separatelyHandled as part of click sequence


15. Click and Hold with ID Locator

WebElement element = driver.findElement(

    By.id("dragSource")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


16. Click and Hold with Name Locator

WebElement element = driver.findElement(

    By.name("dragSource")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


17. Click and Hold with Class Name

WebElement element = driver.findElement(

    By.className("draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


18. Click and Hold with CSS Selector

WebElement element = driver.findElement(

    By.cssSelector(".draggable")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


19. Click and Hold with XPath

WebElement element = driver.findElement(

    By.xpath("//div[@id='draggable']")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


20. Click and Hold with Stable Locator

Stable locators improve the reliability of mouse interaction tests.

WebElement element = driver.findElement(

    By.cssSelector("[data-testid='drag-item']")

);

 

new Actions(driver)

    .clickAndHold(element)

    .perform();


21. Click and Hold with moveToElement()

The pointer can first be moved to the required element and then the mouse button can be held.

new Actions(driver)

    .moveToElement(element)

    .clickAndHold()

    .perform();


22. Click and Hold Followed by moveToElement()

This is a common sequence for custom drag-and-drop interactions.

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .perform();


23. Click and Hold Followed by moveByOffset()

The pointer can be moved by a specified offset while the mouse button remains pressed.

new Actions(driver)

    .clickAndHold(source)

    .moveByOffset(200, 100)

    .perform();

Offset-based movement should be used carefully because responsive layouts can change element positions.


24. Click and Hold with Release

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

The sequence represents a complete press, move, and release interaction.


25. Understanding release()

The release() method releases the currently held mouse button. It is particularly important when using clickAndHold() for drag-and-drop or custom mouse interactions.

actions.clickAndHold(source)

       .moveToElement(target)

       .release()

       .perform();


26. Click and Hold for Dragging an Element

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveToElement(target)

    .release()

    .perform();


27. Manual Drag and Drop Using Click and Hold

Manual drag and drop can be useful when the direct dragAndDrop() method does not behave as expected with a custom component.

Actions actions = new Actions(driver);

 

actions.moveToElement(source)

       .clickAndHold()

       .moveToElement(target)

       .release()

       .perform();


28. Click and Hold for Sortable Lists

Sortable lists often require an item to remain selected while it is moved to another position.

WebElement firstItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(1)")

);

 

WebElement secondItem = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(2)")

);

 

new Actions(driver)

    .clickAndHold(firstItem)

    .moveToElement(secondItem)

    .release()

    .perform();


29. Click and Hold in a Kanban Board

Kanban boards use drag interactions to move tasks between columns.

WebElement task = driver.findElement(

    By.cssSelector(".task-card")

);

 

WebElement inProgress = driver.findElement(

    By.id("inProgress")

);

 

new Actions(driver)

    .clickAndHold(task)

    .moveToElement(inProgress)

    .release()

    .perform();


30. Click and Hold in a Shopping Cart

An e-commerce interface may allow a product to be dragged into a shopping cart.

WebElement product = driver.findElement(

    By.cssSelector(".product-card")

);

 

WebElement cart = driver.findElement(

    By.id("cart")

);

 

new Actions(driver)

    .clickAndHold(product)

    .moveToElement(cart)

    .release()

    .perform();


31. Click and Hold for a Slider

Some sliders require the user to press and hold the slider handle while moving it horizontally or vertically.

WebElement slider = driver.findElement(

    By.id("priceSlider")

);

 

new Actions(driver)

    .clickAndHold(slider)

    .moveByOffset(100, 0)

    .release()

    .perform();


32. Horizontal Slider Example

WebElement sliderHandle = driver.findElement(

    By.cssSelector(".slider-handle")

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(150, 0)

    .release()

    .perform();


33. Vertical Slider Example

WebElement sliderHandle = driver.findElement(

    By.cssSelector(".vertical-slider-handle")

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(0, 100)

    .release()

    .perform();


34. Click and Hold with Target Offset

Some custom components respond only when the pointer is released at a specific location inside the target.

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target, 20, 20)

    .release()

    .perform();


35. Click and Hold with Intermediate Movement

Complex applications may require the pointer to move through an intermediate location before reaching the final destination.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .moveByOffset(100, 0)

    .moveToElement(target)

    .release()

    .perform();


36. Click and Hold with Pause

A pause can be inserted into an Actions sequence when the application requires a short interval during the interaction.

new Actions(driver)

    .moveToElement(source)

    .clickAndHold()

    .pause(Duration.ofMillis(500))

    .moveToElement(target)

    .release()

    .perform();


37. Required Duration Import

import java.time.Duration;


38. Why Use Pause Carefully?

Pause can help with specific UI behaviors, but it should not be used as a replacement for proper synchronization. Prefer condition-based explicit waits whenever the application exposes a state that can be waited for.


39. Click and Hold with Explicit Wait

Dynamic web applications may load the element after the initial page load. Explicit waits can help synchronize the test before starting the interaction.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


40. Explicit Wait Imports

import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;


41. Click and Hold on Dynamic Elements

When the DOM changes dynamically, locate the element after the required application state has been reached.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector(".dynamic-source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


42. Avoid Thread.sleep()

Hard-coded delays can make tests unnecessarily slow and may still fail if the application takes longer than the selected delay.

Thread.sleep(3000);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

Prefer explicit waits that synchronize with an actual UI condition.


43. Click and Hold with Visibility Check

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement source = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


44. Click and Hold with Element Clickability

WebElement source = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.elementToBeClickable(

        By.id("source")

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


45. Click and Hold Inside an iframe

If the element exists inside an iframe, Selenium must switch into that iframe before interacting with the element.

driver.switchTo().frame("dragFrame");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

driver.switchTo().defaultContent();


46. Click and Hold in Nested Frames

driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

driver.switchTo().defaultContent();


47. Click and Hold with Scrolling

If the required element is outside the visible viewport, it may be useful to scroll it into view before performing the mouse interaction.

WebElement source = driver.findElement(

    By.id("source")

);

 

((JavascriptExecutor) driver).executeScript(

    "arguments[0].scrollIntoView({block:'center'});",

    source

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


48. JavaScript Executor Import

import org.openqa.selenium.JavascriptExecutor;


49. Click and Hold on Responsive Applications

Responsive layouts can change element positions and dimensions. Element-based interactions are generally more maintainable than hard-coded screen coordinates.

WebElement source = driver.findElement(

    By.cssSelector(".responsive-source")

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


50. Click and Hold with Custom UI Components

Modern applications may implement draggable components using JavaScript frameworks. The exact event handling determines whether Selenium's native Actions sequence works correctly.

WebElement source = driver.findElement(

    By.cssSelector(".custom-draggable")

);

 

WebElement target = driver.findElement(

    By.cssSelector(".custom-target")

);

 

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();


51. Click and Hold and HTML5 Drag Behavior

HTML5 drag-and-drop components may use browser drag events such as dragstart, dragover, and drop. A normal pointer sequence may not always produce the exact application behavior expected by a custom implementation.

<div id="source" draggable="true">

    Drag Me

</div>

 

<div id="target">

    Drop Here

</div>


52. Troubleshooting Click and Hold

If the interaction does not work as expected, inspect the application's DOM and event behavior before changing the automation approach.

  • Verify the source locator.
  • Check whether the element is visible.
  • Check whether an overlay is covering the element.
  • Verify that the element is enabled.
  • Confirm that the correct iframe is selected.
  • Check whether the application requires scrolling.
  • Try a complete move and release sequence.
  • Validate the application result.


53. Click and Hold with dragAndDrop()

The direct dragAndDrop() method can be used when a complete source-to-target drag operation is required.

new Actions(driver)

    .dragAndDrop(source, target)

    .perform();

Manual clickAndHold() is useful when more control over the interaction sequence is required.


54. Direct Drag and Drop vs Click and Hold

AspectdragAndDrop()clickAndHold()
PurposeComplete drag-and-drop operationPress and maintain mouse button
ControlLess granular controlMore granular control
MovementBuilt into operationCan be customized
ReleaseIncluded in complete operationCan be performed separately
Use caseStandard drag and dropCustom mouse sequences


55. Click and Hold for Mouse-Based Workflows

Click and hold can be useful when a workflow requires the user to press a control and maintain the press while another UI state changes.

  • Drag handles.
  • Sliders.
  • Sortable lists.
  • Kanban cards.
  • Dashboard widgets.
  • Custom graphical controls.


56. Click and Hold for Dashboard Widgets

WebElement widget = driver.findElement(

    By.id("salesWidget")

);

 

WebElement targetArea = driver.findElement(

    By.id("dashboardArea")

);

 

new Actions(driver)

    .clickAndHold(widget)

    .moveToElement(targetArea)

    .release()

    .perform();


57. Click and Hold for File Manager

A web-based file manager may allow a user to select and move a file while holding the mouse button.

WebElement file = driver.findElement(

    By.cssSelector(".file-item")

);

 

WebElement folder = driver.findElement(

    By.cssSelector(".destination-folder")

);

 

new Actions(driver)

    .clickAndHold(file)

    .moveToElement(folder)

    .release()

    .perform();


58. Click and Hold for Calendar Scheduling

Some scheduling interfaces allow users to move appointments by dragging them across a calendar.

WebElement appointment = driver.findElement(

    By.cssSelector(".appointment")

);

 

WebElement timeSlot = driver.findElement(

    By.cssSelector(".time-slot-14")

);

 

new Actions(driver)

    .clickAndHold(appointment)

    .moveToElement(timeSlot)

    .release()

    .perform();


59. Click and Hold for Task Management

WebElement task = driver.findElement(

    By.cssSelector(".task-card")

);

 

WebElement completed = driver.findElement(

    By.id("completed")

);

 

new Actions(driver)

    .clickAndHold(task)

    .moveToElement(completed)

    .release()

    .perform();


60. Click and Hold for E-Commerce Sorting

WebElement product = driver.findElement(

    By.cssSelector(".product-item")

);

 

WebElement destination = driver.findElement(

    By.cssSelector(".comparison-area")

);

 

new Actions(driver)

    .clickAndHold(product)

    .moveToElement(destination)

    .release()

    .perform();


61. Click and Hold with Assertions

The test should validate the result of the interaction instead of only checking whether Selenium executed the Actions sequence.

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement result = driver.findElement(

    By.id("successMessage")

);

 

Assert.assertTrue(

    result.isDisplayed(),

    "Expected result was not displayed"

);


62. Click and Hold with Text Validation

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement message = driver.findElement(

    By.id("message")

);

 

Assert.assertEquals(

    message.getText(),

    "Item moved successfully"

);


63. Click and Hold with Visibility Validation

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

 

WebElement resultPanel = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("resultPanel")

    )

);

 

Assert.assertTrue(resultPanel.isDisplayed());


64. Click and Hold with TestNG

@Test

public void verifyClickAndHoldInteraction() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

    Assert.assertTrue(

        driver.findElement(By.id("result")).isDisplayed()

    );

}


65. TestNG Imports

import org.testng.Assert;

import org.testng.annotations.Test;


66. Click and Hold in Page Object Model

In the Page Object Model, the mouse interaction can be encapsulated inside a page class so that tests remain readable and reusable.

public void moveItemToTarget() {

 

    WebElement source = driver.findElement(

        By.id("source")

    );

 

    WebElement target = driver.findElement(

        By.id("target")

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}


67. Page Object Model Example

public class KanbanPage {

 

    private WebDriver driver;

 

    private By task = By.id("task");

    private By inProgress = By.id("inProgress");

 

    public KanbanPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void moveTaskToInProgress() {

 

        WebElement source =

            driver.findElement(task);

 

        WebElement target =

            driver.findElement(inProgress);

 

        new Actions(driver)

            .clickAndHold(source)

            .moveToElement(target)

            .release()

            .perform();

    }

}


68. Calling Page Object Method

@Test

public void moveTask() {

 

    KanbanPage page =

        new KanbanPage(driver);

 

    page.moveTaskToInProgress();

}


69. Reusable Click and Hold Utility

public class ActionUtils {

 

    private WebDriver driver;

 

    public ActionUtils(WebDriver driver) {

        this.driver = driver;

    }

 

    public void clickAndHold(WebElement element) {

 

        new Actions(driver)

            .clickAndHold(element)

            .perform();

    }

}


70. Reusable Drag Utility

public void clickAndHoldAndMove(

    WebElement source,

    WebElement target

) {

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}


71. Utility Using Locators

public void clickAndHoldAndMove(

    By sourceLocator,

    By targetLocator

) {

 

    WebElement source =

        driver.findElement(sourceLocator);

 

    WebElement target =

        driver.findElement(targetLocator);

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}


72. Utility with Explicit Wait

public void clickAndHoldAndMove(

    By sourceLocator,

    By targetLocator

) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement source = wait.until(

        ExpectedConditions.elementToBeClickable(

            sourceLocator

        )

    );

 

    WebElement target = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            targetLocator

        )

    );

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

}


73. Click and Hold Exception Handling

Unexpected UI states can cause Selenium exceptions. Frameworks should capture useful information when an interaction fails.

try {

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

} catch (Exception e) {

 

    System.out.println(

        "Click and hold operation failed: "

        + e.getMessage()

    );

}


74. ElementNotInteractableException

This exception can occur when the source element cannot currently receive the intended interaction.

  • Element is hidden.
  • Element is disabled.
  • Element is outside the required UI state.
  • Another element covers it.
  • The page has not finished loading.


75. ElementClickInterceptedException

An overlay, popup, modal, tooltip, or another element can interfere with the mouse interaction.

  • Wait for the overlay to disappear.
  • Verify element visibility.
  • Check the page state.
  • Scroll the element into view when appropriate.
  • Use stable locators.


76. StaleElementReferenceException

A stale element exception may occur if the DOM changes after the source element was located.

WebElement source = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.elementToBeClickable(

            By.id("source")

        )

    )

);

 

new Actions(driver)

    .clickAndHold(source)

    .perform();


77. MoveTargetOutOfBoundsException

This exception can occur when the requested pointer movement cannot be completed within the available browser viewport or element coordinates.

Possible solutions include:

  • Scroll the element into view.
  • Avoid unnecessary coordinate offsets.
  • Use element-based movement.
  • Verify responsive layout behavior.


78. Click and Hold with Screenshot on Failure

try {

 

    new Actions(driver)

        .clickAndHold(source)

        .moveToElement(target)

        .release()

        .perform();

 

} catch (Exception e) {

 

    File screenshot =

        ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

    System.out.println(

        "Interaction failed: " + e.getMessage()

    );

}


79. Screenshot Imports

import java.io.File;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;


80. Logging Click and Hold Actions

Logging can help identify whether the failure occurred while locating, pressing, moving, or releasing the mouse.

System.out.println("Locating source element");

 

WebElement source = driver.findElement(

    By.id("source")

);

 

System.out.println("Starting click and hold");

 

new Actions(driver)

    .clickAndHold(source)

    .perform();

 

System.out.println("Mouse button is being held");


81. Click and Hold Best Practices

  • Use the Actions class for advanced mouse interactions.
  • Use stable source locators.
  • Use explicit waits for dynamic elements.
  • Scroll elements into view when necessary.
  • Use element-based movement instead of fixed coordinates.
  • Release the mouse button when the interaction is complete.
  • Validate the expected application state.
  • Keep reusable Actions logic inside utilities.
  • Keep page-specific locators inside page objects.
  • Capture screenshots when important interactions fail.


82. Common Mistakes

  • Using click() instead of clickAndHold() for a continuous interaction.
  • Forgetting to release the mouse button.
  • Using unstable XPath expressions.
  • Ignoring dynamic page loading.
  • Not switching into an iframe.
  • Ignoring overlays and popups.
  • Using unnecessary hard-coded sleeps.
  • Relying heavily on screen coordinates.
  • Not validating the result.
  • Duplicating Actions code across multiple tests.


83. Click and Hold vs Fixed Coordinates

AspectElement-BasedFixed Coordinates
MaintainabilityGenerally betterLower
Responsive layoutsMore suitableRisky
Locator dependencyYesNo
Layout changesUsually more tolerantCan break easily
Recommended usagePreferredOnly when necessary


84. Click and Hold and Responsive Testing

When testing responsive applications, element positions can change across viewport sizes. Prefer locating the element and using Actions methods instead of depending on absolute screen coordinates.

WebElement handle = driver.findElement(

    By.cssSelector(".slider-handle")

);

 

new Actions(driver)

    .clickAndHold(handle)

    .moveByOffset(100, 0)

    .release()

    .perform();


85. Click and Hold in Cross-Browser Testing

Advanced mouse interactions should be tested on the browsers supported by the application.

BrowserValidation
ChromeClick and hold behavior
FirefoxClick and hold behavior
EdgeClick and hold behavior


86. Click and Hold in Parallel Testing

Parallel tests should use independent WebDriver instances and appropriate test data isolation. A mouse interaction performed by one browser session should not affect another session.


87. Click and Hold in Automation Framework

A professional Selenium framework should separate page elements, reusable actions, waits, and test scenarios.

  • Page classes contain page-specific locators.
  • Action utilities contain reusable mouse interactions.
  • Wait utilities contain synchronization logic.
  • Test classes contain business scenarios.
  • Reports capture execution results.


88. Recommended Framework Structure

src

├── main

│   └── java

│       ├── pages

│       ├── utilities

│       ├── waits

│       └── base

└── test

    └── java

        ├── tests

        └── testdata


89. Practical Test Scenario

Consider a Kanban application where a tester needs to move a task from the To Do column to the In Progress column.

  1. Launch the browser.
  2. Open the application.
  3. Login with valid credentials.
  4. Navigate to the Kanban board.
  5. Locate the task.
  6. Locate the In Progress column.
  7. Wait until both elements are ready.
  8. Click and hold the task.
  9. Move the pointer to the destination column.
  10. Release the mouse button.
  11. Wait for the board to update.
  12. Verify that the task moved successfully.


90. Practical Kanban Example

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement task = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.cssSelector("div[data-task='TASK1001']")

    )

);

 

WebElement inProgress = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("inProgress")

    )

);

 

new Actions(driver)

    .moveToElement(task)

    .clickAndHold()

    .moveToElement(inProgress)

    .release()

    .perform();

 

WebElement result = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.cssSelector("div[data-task='TASK1001']")

    )

);

 

Assert.assertTrue(

    result.isDisplayed(),

    "Task was not displayed after the interaction"

);


91. Practical Slider Example

WebElement sliderHandle = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.elementToBeClickable(

        By.cssSelector(".slider-handle")

    )

);

 

new Actions(driver)

    .clickAndHold(sliderHandle)

    .moveByOffset(120, 0)

    .release()

    .perform();


92. Practical Sortable List Example

WebElement item1 = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(1)")

);

 

WebElement item3 = driver.findElement(

    By.cssSelector(".sortable-item:nth-child(3)")

);

 

new Actions(driver)

    .clickAndHold(item1)

    .moveToElement(item3)

    .release()

    .perform();


93. Practical Calendar Example

WebElement appointment = driver.findElement(

    By.id("appointment")

);

 

WebElement newSlot = driver.findElement(

    By.cssSelector("[data-time='14:00']")

);

 

new Actions(driver)

    .clickAndHold(appointment)

    .moveToElement(newSlot)

    .release()

    .perform();


94. Sample Test Case

Test Case IDScenarioExpected Result
TC-CLICKHOLD-001Hold draggable taskMouse remains pressed during interaction
TC-CLICKHOLD-002Move task to another columnTask is moved successfully
TC-CLICKHOLD-003Move slider handleSlider value changes
TC-CLICKHOLD-004Move sortable itemItem changes position
TC-CLICKHOLD-005Interact with dynamic elementElement is located and interaction succeeds


95. Click and Hold Test Case Template

Test Case ID: TC-CLICKHOLD-001

Title: Verify Click and Hold Interaction

Precondition: User is logged in

Steps:

1. Navigate to the required page

2. Locate the source element

3. Wait until the element is interactable

4. Move the pointer to the element

5. Click and hold the element

6. Perform the required movement

7. Release the mouse button

8. Validate the expected result

 

Expected Result:

The application should respond correctly to

the complete click-and-hold interaction.


96. Interview Question: What is Click and Hold in Selenium?

Click and Hold is an advanced mouse interaction in Selenium where the mouse button is pressed on an element and remains pressed until another action, such as movement or release, is performed.


97. Interview Question: Which Class is Used for Click and Hold?

The org.openqa.selenium.interactions.Actions class is commonly used to perform click-and-hold and other advanced mouse interactions.


98. Interview Question: What is the Syntax of clickAndHold()?

new Actions(driver)

    .clickAndHold(element)

    .perform();


99. Interview Question: How is Click and Hold Used for Drag and Drop?

new Actions(driver)

    .clickAndHold(source)

    .moveToElement(target)

    .release()

    .perform();

The sequence presses the mouse button on the source, moves to the target while keeping the button pressed, and then releases it.


100. Interview Question: Why is release() Used?

The release() method releases the currently held mouse button. It is commonly paired with clickAndHold() when creating manual drag-and-drop or other continuous mouse interactions.


101. Interview Question: Difference Between click() and clickAndHold()?

click() performs a normal click interaction, while clickAndHold() presses the mouse button and keeps it pressed until the interaction is released or otherwise completed.


102. Quick Revision

  • Click and Hold is an advanced mouse interaction.
  • It is provided through Selenium's Actions class.
  • Use clickAndHold() to press and maintain the mouse button.
  • Use moveToElement() to move while holding.
  • Use moveByOffset() for relative pointer movement.
  • Use release() to release the mouse button.
  • Use perform() to execute the Actions sequence.
  • Click and Hold is useful for drag and drop.
  • It is useful for sliders and sortable components.
  • Use explicit waits for dynamic elements.
  • Use stable locators.
  • Validate the application result after the interaction.


103. Click and Hold Checklist

  • Source element identified correctly.
  • Stable locator used.
  • Element is visible.
  • Element is interactable.
  • Required wait implemented.
  • Required iframe handled.
  • Element is scrolled into view when necessary.
  • Actions object created.
  • Mouse button held using clickAndHold().
  • Required movement performed.
  • Mouse button released.
  • Expected result validated.
  • Screenshot captured on important failures.
  • Reusable utility used where appropriate.


104. Practical Mini Project

Project: Kanban Task Click and Hold Automation

Automate a Kanban board where a task is selected using click and hold, moved to the In Progress column, and released.

  1. Launch the browser.
  2. Open the Kanban application.
  3. Login with valid credentials.
  4. Navigate to the board.
  5. Locate the task using a stable locator.
  6. Locate the In Progress column.
  7. Wait for both elements.
  8. Move the pointer to the task.
  9. Click and hold the task.
  10. Move the pointer to the destination column.
  11. Release the mouse button.
  12. Wait for the UI update.
  13. Validate that the task appears in the destination.
  14. Capture a screenshot if the test fails.
  15. Generate the test report.

@Test

public void verifyClickAndHoldTaskMove() {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    WebElement task = wait.until(

        ExpectedConditions.elementToBeClickable(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    WebElement inProgress = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("inProgress")

        )

    );

 

    new Actions(driver)

        .moveToElement(task)

        .clickAndHold()

        .moveToElement(inProgress)

        .release()

        .perform();

 

    WebElement movedTask = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.cssSelector("div[data-task='TASK1001']")

        )

    );

 

    Assert.assertTrue(

        movedTask.isDisplayed(),

        "Task was not displayed after click and hold operation"

    );

}


105. Conclusion

Click and Hold is an important Selenium WebDriver mouse interaction for applications where the mouse button must remain pressed while another action is performed. The Selenium Actions class provides the clickAndHold() method for creating this type of interaction.

Click and Hold becomes especially useful when combined with moveToElement(), moveByOffset(), and release(). This combination provides greater control over custom drag-and-drop operations, sliders, sortable lists, Kanban boards, dashboards, calendar scheduling, and other interactive components.

Reliable automation should use stable locators, explicit waits, correct iframe handling, element-based movement, proper release of the mouse button, and assertions that verify the final application state.

Recommended Selenium Learning Resources:

Selenium Training Course | Register for Course Demo

whatsapp